package main

import (
	"fmt"
	"sync"
	"sync/atomic"
	"time"
)

type task struct {
	f func() error
}

type pool struct {
	capacity      int64
	runing_worker int64
	work_queue    chan *task
	sync.Mutex
}

func NewPool(capacity int64, task_capacity int) *pool {
	return &pool{
		capacity:   capacity,
		work_queue: make(chan *task, task_capacity),
	}
}

func Newtask(f_task func() error) *task {
	return &task{f: f_task}
}

// 获取进程池的容量
func (p *pool) getcap() int64 {
	return p.capacity
}

// 给进程池数加一
func (p *pool) sub_work() {
	atomic.AddInt64(&p.runing_worker, 1)
}

// 给进程池减一
func (p *pool) inc_work() {
	atomic.AddInt64(&p.capacity, -1)
}

// 获取正在工作的进程池的数量
func (p *pool) get_worker() int64 {
	return atomic.LoadInt64(&p.runing_worker)
}

// 程序运行
func (p *pool) run() {
	p.sub_work()
	go func() {
		defer p.sub_work()

		for task := range p.work_queue {
			task.f()
		}
	}()

}

// addtask 往协程池中添加任务
func (p *pool) addtask(task *task) {
	p.Lock()
	defer p.Unlock()
	if p.get_worker() < p.getcap() {
		task.f()
	}
	p.work_queue <- task
}

func main() {
	//创建任务池
	pool := NewPool(3, 10)
	for i := 0; i < 20; i++ {
		idx := i
		fmt.Println(idx)
		pool.addtask(Newtask(func() error {
			fmt.Println("i am task\n")
			return nil
		}))
	}
	time.Sleep(1 * time.Second)
	fmt.Println("协程池结束")

}
